<template>
  <el-form-item :label="config.label" :required="config.required">
    <div>
      <div class="form-table" v-if="list && list.length">
        <div class="head">
          <div v-for="field in config.children" :key="field.prop" :style="`width:${field.width}`">
            {{ field.label }}
          </div>
          <div></div>
        </div>
        <div v-for="(,index) in list" :key="index">
          <div v-for="field in config.children" :key="field.prop" :style="`width:${field.width}`">
            <field v-model="list[index][field.prop]" v-bind="{
              config: field,
              labelWidth: '0px',
              prop: `${config.prop}.${index}.${field.prop}`
            }" />
          </div>
          <div style="width: 150px">
            <el-button @click="addItem(index)">添加</el-button>
            <el-button @click="removeItem(index)">删除</el-button>
          </div>
        </div>
      </div>
      <el-button v-else @click="addItem(0)">添加 </el-button>
    </div>
  </el-form-item>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import type { FieldType } from './type.d';
import Field from './field.vue';
const { config, modelValue } = defineProps<{
  config: FieldType;
  modelValue?: any[];
}>();
const emit = defineEmits(['update:modelValue']);
const checkDefaultValue = () => {
  if (modelValue) return modelValue;
  if (config.default) return config.default;
  return [];
};
const list = ref(checkDefaultValue());
watch(
  list,
  () => {
    emit('update:modelValue', list.value);
  },
  { immediate: true }
);
watch(
  () => modelValue,
  () => {
    list.value = modelValue;
  },
  { deep: true }
);

const addItem = i => {
  if (!list.value) list.value = [];
  list.value.splice(i + 1, 0, {});
};

const removeItem = i => {
  list.value.splice(i, 1);
};
</script>

<style lang="less" scoped>
.form-table {
  &>div {
    gap: 12px;
    display: flex;
    align-items: center;
    margin-bottom: 20px;

    &.head {
      font-weight: 600;
      margin-bottom: 0;
    }

    &:last-child {
      margin-bottom: 0;
    }

    &>div {
      flex: 1;
    }
  }
}
</style>
